'''
Created on 21/04/2009

@author: eh01
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logging import yarralogging
import httplib
import os
import re

class HTTPRequestPOSTLoggingHandler(BaseEventHandler):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()
        form_data_dsts = dso.get_dsts(subject=dsconstants.SUBJECT_FORM_DATA)
        
        for form_data_dst in form_data_dsts:
            predicate = form_data_dst.get_predicate()
            matches = re.match('^logger_(\w+)', predicate)
            if matches:
                new_level = int(form_data_dst.get_literal())
                logger_name = matches.group(1)
                yarralogging.update_log_level(new_level, logger_name)
                
        # get the html
        relative_path = "../../../pages/hub/admin.html"        
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        # create new dso        
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_template_string, 
                                                               http_request, 
                                                               lock)
        event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE            
        event = Event(event_type, new_dso)
        EventManager().add_event(event)            
            
        